from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver import ChromeOptions
# 规避被检测的风险
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
browser = webdriver.Chrome(options=option)
# 通过浏览器的dev_tool在get页面钱将.webdriver属性改为"undefined"
browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {  # 直接滑块消失
    "source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})""",
})
try:
    # 访问页面
    browser.get('https://www.baidu.com')
    input = browser.find_element_by_id('kw')
    input.send_keys('Python')
    input.send_keys(Keys.ENTER)
    wait = WebDriverWait(browser,10)
    wait.until(EC.presence_of_all_elements_located((By.ID,'content_left')))
    print(browser.current_url)
    print(browser.get_cookies())
    print(browser.page_source)#网页源代码
finally:
    browser.close()#浏览器关闭